<?php

    global $mikron;

    $mikron->Schema->Add(dirname(__FILE__).'/schema.xml', 'Схема магазина');

    // если нажата «Отмена» в каком либо диалоге
    if(isset($_REQUEST['cancel']))
    {
        header("Location: ".clearscriptname());
        exit;
    }
    
    class ScenaryStage
    {
        public $code, $desc, $object, $function;
        function __construct($code, $desc, $object, $function)
        {
            $this->code = $code;
            $this->desc = $desc;
            $this->object = $object;
            $this->function = $function;
        }
    }

    class scenary
    {
        private $stages = Array();
        function __construct()
        {
        }
        function AddStage($code, $desc, $object, $function)
        {
            $this->stages[] = new ScenaryStage($code, $desc, $object, $function);
        }
        function ShowStage()
        {
            foreach($this->stages as $stage)
            {
                $object = $stage->object;
                $function = $stage->function;
                $ret = $object->$function();
                if(!$ret)
                {
                    return $object->code;
                }
            }
            $out = ob_get_clean();
            $this->market_data = null;
            $_SESSION['market_data'] = $this->market_data;
            header('Location: /cabinet/');
            exit;
        }
    }

    class market_class
    {
        private $scenary;
        private $market_data;
        function SelectItem()
        {
            $ok = !is_null($this->market_data['item']);
            if(isset($_GET['item']))
            {
                $this->market_data['item'] = $_GET['item'];
                $_SESSION['market_data'] = $this->market_data;
                $ok = true;
            }
            if($ok)
            {
                return true;
            }
        }
        function SelectPuyMethod()
        {
            global $mikron;
            $ok = !is_null($this->market_data['puymethod']);
            if(isset($_REQUEST['puymethod']))
            {
                $this->market_data['puymethod'] = $_REQUEST['puymethod']['puymethod'];
                $_SESSION['market_data'] = $this->market_data;
                $ok = true;
            }
            if($ok)
            {
                return true;
            }
            if(is_object($item = GetMarketItemByCode($this->market_data['item'])))
            {
                if(!is_null($item->description->value))
                {
                    echo $item->description->value;
                }
            }
            $this->market_data['apply'] = null;
            $this->market_data['smsunit'] = null;
            
            ?><h2>Выберите метод оплаты:</h2><?php
            $frm = new html_form('puymethod', 'post', $_SERVER['REQUEST_URI'], null, 1);
            $puymethods = $mikron->Enumerators->getEnum('PAYMENT_METHODS');
            unset($puymethods['webmoney']);
            $frm->addSelectControlFromEnumerator(1, 'puymethod', 'Метод оплаты:', $puymethods);
            $frm->addSubmit('selectpuymethod', 'Далее');
            $frm->end();
            return false;
        }

        function OperatorSelected()
        {
            global $mikron;
            $cabinet = $mikron->Users->CurrentUser()->user;
            $puymethod = $this->market_data['puymethod'];
            if($puymethod != 2)
            {
                $this->market_data['puymethod'] = null;
                return false;
            }
            $smsunit = $this->market_data['smsunit'];
            $cr = new Criteria();
            $cr->Add(new Criterion('item', $this->market_data['item']));
            $smsunits = $mikron->Queries->Query('SMS_BILLING_UNIT', $smsunit, $cr);
            if($smsunits->count() == 0)
            {
                throw new Exception('Ошибка при покупке');
                $this->market_data = Array();
            }
            $smsunit = $smsunits->fetch();
            $smscode = $smsunit->smscode->value;
            $smsunit->smscode->value = str_replace("{{cabinet}}", $cabinet->login->value, $smscode);
            echo $smsunit->toString();
            $smsunit->smscode->value = $smscode;
            $this->market_data['puymethod'] = null;
            return false;
        }

        function Apply()
        {
            global $mikron;
            $ok = !is_null($this->market_data['apply']);
            if($ok)
            {
                return true;
            }
            $code = $this->market_data['item'];
            $puymethod = $this->market_data['puymethod'];
            if(!IsMarketItemCode($code))
            {
                // Неверный товар
                return false;
            }
            if(!IsPaymentMethod($puymethod))
            {
                // Неверный метод оплаты
                $this->market_data['puymethod'] = null;
                return false;
            }
            // SMS-сообщение
            if($puymethod == 2)
            {
                if(!is_null($this->market_data['operator']))
                {
                    return true;
                }
                if(isset($_POST['operator_select']))
                {
                    $pd = $_POST['operator_select'];
                    if(array_key_exists('smsunit', $pd))
                    {
                        $this->market_data['smsunit'] = $pd['smsunit'];
                        return true;
                    }
                }
                $item = GetMarketItemByCode($code);
                ?>
                Вы покупаете «<font class="smsfields"><?php echo $item->title->value; ?></font>»
                с оплатой SMS-сообщением.
                <?php
                $smsunits = $mikron->Queries->Query('SMS_BILLING_UNIT', null, new Criterion('item', $item->id));
                if($smsunits->count() > 0)
                {
                    ?><p>Выберите Вашего оператора сотовой связи:</p><?php
                    $f = new html_form('operator_select', 'post', $_SERVER['REQUEST_URI'], null, 1);
                    $f->addSelectControlFromEntity(1, 'smsunit', 'Оператор', $smsunits);
                    $f->addSubmit('ok_op_sel', 'Далее');
                    ?><script type="text/javascript">
                        // document.operator_select.operator_select[ok_op_sel].disabled=true;
                    </script>
                    <?php
                }
                else
                {
                    ?>Извините, нет ни одного оператора,
                    через которого можно купить
                    выбранный предмет.<?php
                }

            /*
            case 5: // оплата смс-кой товара $_REQUEST['incode']
                    $incode = $_REQUEST['incode'];
                    if(!IsMarketItemCode($incode))
                    {
                        ?>
                        {{nicewindow style=silver caption=Ошибка}}
                        <p>Для покупки выбран несуществующий товар.</p>
                        <input type="hidden" name="stepfrom" value="1">
                        <input type="submit" name="back" value="&larr; Назад">
                        {{/nicewindow}}
                        <?php
                        break;
                    }
                    $chipsname = getChipsName($incode);
                    $phoneoperator_id = (int)$_REQUEST['phoneoperator'];
                    $phoneoperator = null;
                    $smsunits = $mikron->Queries->Query("SMS_BILLING_UNIT");
                    $smsunits2 = Array();
                    while($smsunit = $smsunits->fetch())
                    {
                        $smsunits2[] = $smsunit;
                        if($smsunit->phoneoperator->value->id == $phoneoperator_id)
                        {
                            $phoneoperator = $smsunit->phoneoperator->value;
                        }
                    }
                    if($phoneoperator == null)
                    {
                        ?>
                        {{nicewindow style=silver caption="Ошибка"}}
                        <p>Для покупки выбран несуществующий оператор.</p>
                        <input type="hidden" name="incode" value="<?php echo $incode ?>">
                        <input type="hidden" name="paymentmethod" value="2">
                        <input type="hidden" name="stepfrom" value="4">
                        <input type="submit" name="back" value="&larr; Назад">
                        {{/nicewindow}}
                        <?php
                        break;
                    }
                    ?>
                    {{nicewindow style=silver caption="Покупка"}}
                    <?php
                    reset($smsunits);
                    foreach($smsunits2 as $smsunit)
                    {
                        if(($incode == $smsunit->item->value->code->value) && ($smsunit->phoneoperator->value->id == $phoneoperator_id))
                        {
                            $smscode = $smsunit->smscode->value;
                            $smsunit->smscode->value = str_replace("{{cabinet}}", $cabinet->login->value, $smscode);
                            echo $smsunit->toString();
                            $smsunit->smscode->value = $smscode;
                            break;
                        }
                    }                    
                    ?><p><input type="submit" name="cancel" value="Завершить покупку"></p>
                    {{/nicewindow}}
                    <?php
                break;
                */

                
                
                
                
                
                
                
                
                
                
                
                
                
            }
            // Баланс аккаунта
            if($puymethod == 3)
            {
                $item = GetMarketItemByCode($code);
                $amount = $item->amount->value;
                if($amount > $mikron->Users->CurrentUser()->user->amount->value)
                {
                    $need = round($amount/100, 2).' руб';
                    $your = round($mikron->Users->CurrentUser()->user->amount->value/100, 2).' руб';
                    $this->market_data['puymethod'] = null;
                    echo "{{nicewindow style=error caption=Внимание}}Недостаточно денег на балансе.
                    Необходимо $need, а у Вас $your.{{/nicewindow}}";
                    unset($_REQUEST);
                    $this->SelectPuyMethod();
                    return false;
                }
                try
                {
                    $this->Buy($item);
                    $this->market_data['apply'] = null;
                    $this->market_data['puymethod'] = null;
                    $this->market_data['smsunit'] = null;
                    echo $item->DisplayName(), ' успешно куплен.';
                }
                catch(Exception $ex)
                {
                    if($ex->getCode() == 1029)
                    {
                        ?>У Вас уже есть <?php echo $item->DisplayName(), '.';
                    }
                    else
                    {
                        ?>Ошибка при покупке, попробуйте еще раз.<?php
                    }
                }
            }
        }
        function Buy($item)
        {
            global $mikron;
            if($mikron->Users->CurrentUser()->hasRole($item->code->value))
            {
                throw new Exception('Роль уже существует.', 1029);
            }
            $amount = $item->amount->value;
            $user = $mikron->Users->CurrentUser()->user;
            $foplog = ChangeCabinetBalance($user, 1, -$amount, 0, 0, 0, 0);
            $foplog->amount->value = -$amount;
            OperationLogEcp($foplog, $user);
            $cabinet->amount->value -= $amount;
            $newrole = $mikron->ACL->addRoleToUser($user, $item->code->value, 30);
            $mikron->EntityManager->Save(Array($foplog, $user, $newrole));
            $mikron->ACL->Refresh();
        }
        function __construct()
        {

            $this->scenary = new scenary();
            $this->market_data = Array('item'=>null, 'puymethod'=>null, 'apply'=>null, 'smsunit'=>null);
            if(isset($_SESSION['market_data']))
            {
                $this->market_data = $_SESSION['market_data'];
            }

            $this->scenary->AddStage('select_item', 'Выбор товара', $this, 'SelectItem');
            $this->scenary->AddStage('select_puy_method', 'Выбор метода оплаты', $this, 'SelectPuyMethod');
            $this->scenary->AddStage('apply', 'Обработка', $this, 'Apply');
            $this->scenary->AddStage('sms_operator_selected', 'Выбор оператора', $this, 'OperatorSelected');

            ?><h1>Покупка:</h1><?php
            $run_code = $this->scenary->ShowStage();

            $_SESSION['market_data'] = $this->market_data;

            return;

            global $mikron;
            // текущий активный кабинет
            $cabinet = $mikron->Users->CurrentUser()->user;
            $webmoney_order_present = false;
            $step = isset($_REQUEST['step'])?(int)$_REQUEST['step']:1;
            if(isset($_REQUEST['back']))
            {
                $step = isset($_REQUEST['stepfrom'])?(int)$_REQUEST['stepfrom']:$step;
            }
            $invisible = false;
            $chips = $mikron->Queries->Query("MARKET_ITEM", null, new Criterion('forsale', 1)); // фишки
            $cabinetamount = (int)$cabinet->amount->value;
            if($cabinet->lockmarket->value==1)
            {
                ?>
                {{nicewindow style=error caption=Внимание}}Вам запрещено посещение магазина.
                Свяжитесь с администрацией сайта.{{/nicewindow}}
                <?php
                return null;
            }
            $invisible = show_messages();
            if($invisible) { ?><div id="buyblock" style="display: none; "><?php }
            buyfunc($cabinet, $mikron, $chips, $cabinetamount, $step, $webmoney_order_present);
            if($invisible) { ?></div><?php }
        }
    }

    function echoerror($ertext, $stepfrom)
    {

        ?>
        {{nicewindow style=error caption="Ошибка"}}
        <?php 
        $tbl = new html_table(1, null, "100%", 0, 4);
        $tbl->newcol($ertext);
        $tbl->newcol();
        ?>
        <input type="hidden" name="stepfrom" value="<?php echo $stepfrom; ?>">
        <input type="submit" name="back" value="&larr; Назад">
        <?php  $tbl->end(); ?>
        {{/nicewindow}}
        <?php
            
    }

    function startokform()
    {
        ?><div id="okdisplay"><?php
        startxform("Выполнено", clearscriptname(), "okform", "get", "_silver", true);
        ?>
        <table cellspacing="0" cellpadding="4">
        <tr><td>
        <?php
    }

    function endokform()
    {
        ?>
        </td></tr>
        <tr><td>
            <input type="submit" onclick="okdisplay.style.display='none'; buyblock.style.display=''; return false;" value="Закрыть">
        </table>
        <?php endxform(true); ?></div><?php
    }

    function show_messages()
    {
        // если выводится сообщение об успешном действии
        if(array_key_exists("ok", $_REQUEST))
        {
            $ok = $_REQUEST['ok'];
            switch($ok)
            {
                case "buy":
                    unset($_REQUEST['ok']);
                    startokform();
                    ?>Покупка завершена успешно.<?php
                    endokform();
                    return true;
                    break;
                case "webmoney": case "order":
                    break;
            }
            
        }

        // если выводится сообщение об ошибке
        if(array_key_exists("error", $_REQUEST))
        {
            $error = $_REQUEST['error'];
            unset($_REQUEST['error']);
            startxform("Внимание", clearscriptname(), "okform", "get", "_silver");
            switch($error)
            {
                case "noorder":
                    ?>Указанной покупки не существует.<?php
                    break;
                case "nomoney";
                    ?>Ошибка оформления заявки.
                    Недостаточно средств.<?php
                    break;
            }
            ?><br /><input type="submit" value="Закрыть"><?php
            endxform();
            return true;
        }
        return false;
    }

    function startxform($caption, $action, $formname, $method = "post", $color = "_green", $inframe = false)
    {
        if($inframe)
        {
            echo "{{nicewindow style=$color caption=\"$caption\"}}";
        }
        echo "<form action=\"$action\" method=\"$method\" name=\"$formname\">";
    }

    function endxform($inframe = false)
    {
        echo "</form>";
        if($inframe)
        {
            ?>{{/nicewindow}}<?php
        }
    }

    // обработчик покупки
    function buyfunc($cabinet, $mikron, $chips, $cabinetamount, $step, $order_present)
    {
        $maxwebmoneyamount = 300;
        if($order_present)
        {
            startxform("Внимание", clearscriptname(), "okform", "get", "_silver");
            $tbl = new html_table(1, "table4");
            $tbl->newcol("У Вас уже есть неоплоченная покупка. Оплатите, либо отмените ее.");
            $tbl->newcol();
                ?><br /><input type="submit" value="Закрыть"><?php
            $tbl->end();
            endxform();
            return;
        }
        startxform("Покупка", "/market/?buy", "formbuy");
        // SMS —> 2 -> 4-> 5
        // Purse —> 2 -> 3
        // Webmoney -> 2 -> 6 -> 7
        // Yandex -> 2(4) -> 8 -> 7
        switch($step)
        {
            case 7: case 8:
                // оплата Webmoney либо Yandex
                $paymentmethod = (int)$_REQUEST['paymentmethod'];
                if(isset($_POST['buyamount']) && is_numeric($_POST['buyamount']) && ((int)$_POST['buyamount'] > 0) && isset($_POST['buypurse']) )
                {
                    $amount_sum = (int)$_POST['buyamount'] * 100;
                    if($amount_sum > $maxwebmoneyamount * 100)
                    {
                        $tbl = new html_table(1, null, "100%", 0, 4);
                        $tbl->newcol("Указанная Вами сумма превышает допустимую $maxwebmoneyamount руб.");
                        $tbl->newcol();
                            ?>
                            <input type="hidden" name="paymentmethod" value="<?php echo $paymentmethod; ?>">
                            <input type="hidden" name="stepfrom" value="2">
                            <input type="submit" name="back" value="&larr; Назад">
                            <?php
                        $tbl->end();
                        break;
                    }
                    $purse = $_POST['buypurse'];
                    $cabinetname = $cabinet->login->value;
                    try
                    {
                        $purse2 = quote_smart($purse);
                        $qc = $mikron->EntityManager->QueryCount("T_ORDER", null, "`wmid`=$purse2 AND `status` IN(1,5)");
                        if($qc==0)
                        {
                            $order = new T_ORDER();
                            $order->cabinet->value = $cabinet->id;
                            $order->paymentmethod->value = $paymentmethod;
                            $order->quantity->value = $quantity;
                            $order->amount->value = $amount_sum;
                            switch($paymentmethod)
                            {
                                case 1: // Webmoney
                                    $order->wmid->value = $purse;
                                    break;
                                case 4: // Yandex
                                    $order->yandexmoneyid->value = $purse;
                                    break;
                            }
                            $order->Save();
                            header("Location: index.php");
                            exit;
                        }
                        else
                        {
                            echo "{{nicewindow style=error caption=\"Внимание\"}}";
                            $tbl = new html_table(1, null, "100%", 0, 4);
                            $tbl->newcol("Указанный Вами WMID &ndash; $purse используется в другой активной заявке.");
                            $tbl->newcol();
                                ?>
                                <input type="hidden" name="paymentmethod" value="<?php echo $paymentmethod; ?>">
                                <input type="hidden" name="stepfrom" value="2">
                                <input type="submit" name="back" value="&larr; Назад">
                                <?php
                            $tbl->end();
                            echo "{{/nicewindow}}";
                            break;                            
                        }
                    }
                    catch(Exception $ex)
                    {
                        ?>
                        {{nicewindow style=silver caption=Внимание}}Попробуйте еще раз.{{/nicewindow}}
                        <?php
                    }                    
                }
                else
                {
                    $tbl = new html_table(1, "table4");
                    $tbl->newcol("Не верно заполнена форма.");
                    $tbl->newcol(null, false, false, null, "insideblock");
                        ?>
                        <input type="hidden" name="paymentmethod" value="<?php echo $paymentmethod; ?>">
                        <input type="hidden" name="stepfrom" value="2">
                        <input type="submit" name="back" value="&larr; Назад">
                        <?php
                    $tbl->end();
                }
                break;
            case 1:
                $paymentmethod = null;
                if(isset($_REQUEST['paymentmethod']))
                {
                    if(is_numeric($_REQUEST['paymentmethod']))
                    {
                        $paymentmethod = (int)$_REQUEST['paymentmethod'];
                    }
                }
                $tbl2 = new html_table(1, null, "100%", 0, 4);
                $tbl2->newcol("Выберите способ оплаты:");
                $tbl2->newcol(null, false, false, null, "insideblock");
                    $payment_methods = $mikron->Enumerators->getEnum("PAYMENT_METHODS");
                    foreach($payment_methods as $key => $method)
                    {
                        $disabled = ($key=="purce") && ($cabinet->amount->value < 10) ? "disabled" : null;
                        $value = $method['value'];
                        $description = $method['description'];
                        ?><input type="radio" <?php echo $disabled; ?> <?php if($paymentmethod == $value){echo "checked";}?> onclick="document.formbuy.buynext.disabled=false;" name="paymentmethod" value="<?php echo $value; ?>"> <font class="<?php if(!is_null($disabled)){echo "disabledtext";}?>"><?php echo $description; ?></font><br /><?php
                    }
                $tbl2->newcol();
                    ?>
                    <input type="hidden" name="step" value="2">
                    <input type="hidden" name="stepfrom" value="1">
                    <input type="submit" disabled id="buynext" value="Далее &rarr;">
                    <?php
                $tbl2->end();
                if($paymentmethod==null) { ?>
                <script type="text/javascript">
                    document.formbuy.buynext.disabled=true;
                </script>
                <?php }
                break;
            case 2:
                if(!isset($_REQUEST['paymentmethod']) || !is_numeric($_REQUEST['paymentmethod']))
                {
                    echoerror("Не выбран способ оплаты.", 1);
                    break;
                }
                $paymentmethod = (int)$_REQUEST['paymentmethod'];
                // 1 - webmoney
                // 2 - sms
                // 3 - purse
                // 4 - yandex.money
                switch($paymentmethod)
                {
                    case 1: // оплата с WebMoney
                            ?>
                            {{nicewindow style=silver caption="Оплата&nbsp;через&nbsp;WebMoney"}}
                            {{$WEBMONEY_MARKET_TEXT}}
                            </p>
                            <input type="hidden" name="step" value="8">
                            <input type="hidden" name="stepfrom" value="1">
                            <input type="hidden" name="paymentmethod" value="1">
                            <input type="submit" name="back" value="&larr; Назад">
                            {{/nicewindow}}
                            <?php
                        break;
                    case 4: // оплата с Yandex
                        $tbl2 = new html_table(1, null, "100%", 0, 4);
                        $tbl2->newcol("Выбрана оплата посредством Yandex-кошелька.");
                        $tbl2->newcol("Укажите сумму в рублях, на которую Вы хотите совершить покупку.<br />Сумма не должна превышать $maxwebmoneyamount руб.");
                        $tbl2->newcol(null, false, false, null, "insideblock");
                            ?>
                            <input class="niceinput" name="buyamount" maxlength="6" size="8"> руб.
                            <?php
                        $tbl2->newcol();
                            switch($paymentmethod)
                            {
                                case 1:
                                    ?>Укажите WMID, с которого Вы будете оплачивать:<?php
                                    break;
                                case 4:
                                    ?>Укажите номер кошелька, с которого Вы будете оплачивать:<?php
                                    break;
                            }
                        $tbl2->newcol(null, false, false, null, "insideblock");
                            ?>
                            <input class="niceinput" name="buypurse" maxlength="20" size="20">
                            <?php
                        $tbl2->newcol();
                            ?>
                            <input type="hidden" name="paymentmethod" value="<?php echo $paymentmethod; ?>">
                            <input type="hidden" name="step" value="8">
                            <input type="hidden" name="stepfrom" value="1">
                            <input type="submit" name="back" value="&larr; Назад">
                            <input type="submit" id="buynext" value="Далее &rarr;">
                            <?php
                        $tbl2->end();
                        break;
                    case 2: // оплата по SMS
                        $tbl2 = new html_table(1, null, "100%", 0, 4);
                        $tbl2->newcol("Выбрана оплата SMS-сообщением. Выберите покупаемый Вами шанс:");
                        $tbl2->newcol(null, false, false, null, "insideblock");
                            $incode = null;
                            if(isset($_REQUEST['incode']))
                            {
                                $incode = $_REQUEST['incode'];
                            }
                            if(!IsMarketItemCode($incode))
                            {
                                $incode = null;
                            }
                            $tbl = new html_table(1, null, "100%", 0, 0);
                            $items = Array();
                            while($chip = $chips->fetch())
                            {
                                $forsale = $chip->forsale->value;
                                $forsmssale = $chip->forsmssale->value;
                                if($forsale && $forsmssale)
                                {
                                    $items[] = $chip;
                                }
                            }
                            $c = count($items);
                            foreach($items as $chip)
                            {
                                $amount = $chip->amount->value;
                                $code = $chip->code->value;
                                $title = $chip->title->value;
                                $bonus = $chip->bonus->value;
                                $bonus2 = $bonus;
                                $tbl->newcol();
                                ?><input type="radio" <?php if($code == $incode){?>checked<?php } ?>
                                         name="incode"
                                         onclick="document.formbuy.buynext.disabled = false;"
                                         value="<?php echo $code; ?>"> <?php echo $title, $bonus2;
                                $c--;
                                if($c > 0)
                                {
                                    ?><br />&nbsp;<?php
                                }
                            }
                            $tbl->end();
                        $tbl2->newcol();
                            ?>
                            <input type="hidden" name="paymentmethod" value="2">
                            <input type="hidden" name="step" value="4">
                            <input type="hidden" name="stepfrom" value="1">
                            <input type="submit" name="back" value="&larr; Назад">
                            <input type="submit" id="buynext" value="Далее &rarr;">
                            <?php if($incode==null){ ?>
                            <script type="text/javascript">
                                document.formbuy.buynext.disabled=true;
                            </script>
                            <?php }
                        $tbl2->end();
                        break;
                    case 3: // оплата с внутреннего счета
                        $tbl2 = new html_table(1, null, "100%", 0, 4);
                        $tbl2->newcol("Выберите покупаемый шанс:");
                        $tbl2->newcol(null, false, false, null, "insideblock");

                                while($chip = $chips->fetch())
                                {
                                    $amount = $chip->amount->value;
                                    $code = $chip->code->value;
                                    $title = $chip->title->value;
                                    $forsale = $chip->forsale->value;
                                    if($forsale)
                                    {
                                        ?><input type="radio" name="incode" onclick="formbuytypeselect=true;checkbuyform();"  value="<?php echo $code; ?>"> <?php echo $title; ?><br /><?php
                                    }
                                }
                        $tbl2->newcol("Укажите количество:");
                        $tbl2->newcol(null, false, false, null, "insideblock");
                            ?>
                            <input class="niceinput" id="quantity1" name="quantity" size="4"
                            onKeyUp="if(this.value!=''){formbuyquantityselect = true;}else{formbuyquantityselect=false;}checkbuyform();"> шт.
                            <?php
                        $tbl2->newcol();
                            ?>
                            <input type="hidden" name="paymentmethod" value="3">
                            <input type="hidden" name="step" value="3">
                            <input type="hidden" name="stepfrom" value="2">
                            <input type="hidden" name="stepfrom" value="1">
                            <input type="submit" name="back" value="&larr; Назад">
                            <input type="submit" id="buynext" value="Далее &rarr;">
                            <script type="text/javascript">
                                var formbuytypeselect = false; // тип фишки
                                var formbuyquantityselect = false; // количество покупаемых фишек
                                function checkbuyform()
                                {
                                    document.formbuy.buynext.disabled = !formbuytypeselect || ! formbuyquantityselect;
                                }
                                document.formbuy.buynext.disabled=true;
                            </script>
                            <?php
                        $tbl2->end();
                        break;
                    default:
                            ?>
                            {{nicewindow style=silver caption="Ошибка"}}
                            <p>Попытка взлома. Данный факт занесен в учетную книгу.</p>
                            <input type="hidden" name="step" value="8">
                            <input type="hidden" name="stepfrom" value="1">
                            <input type="hidden" name="paymentmethod" value="1">
                            <input type="submit" name="back" value="&larr; Назад">
                            {{/nicewindow}}
                            <?php
                        break;
                }
                break;
            case 4: // оплата смс-кой товара $_REQUEST['incode']
                    // Выбор оператора
                    $incode = $_REQUEST['incode'];
                    if(!IsMarketItemCode($incode))
                    {
                        ?>
                        {{nicewindow style=silver caption="Ошибка"}}
                        <p>Для покупки выбран несуществующий товар.</p>
                        <input type="hidden" name="stepfrom" value="1">
                        <input type="submit" name="back" value="&larr; Назад">
                        {{/nicewindow}}
                        <?php
                        break;
                    }
                    $chipsname = getChipsName($incode);
                    $tbl2 = new html_table(1, null, "100%", 0, 4);
                    $tbl2->newcol();
                        ?>
                        Вы покупаете «<font class="smsfields"><?php echo $chipsname; ?></font>»
                        с оплатой SMS-сообщением.
                        <input type="hidden" name="incode" value="<?php echo $incode; ?>">
                        <?php
                    $tbl2->newcol("Выберите Вашего оператора сотовой связи:");
                    $tbl2->newcol(null, true, false, null);
                        $su = $mikron->Queries->Query("SMS_BILLING_UNIT");
                        $operators = 0;
                        $smsunits = Array();
                        while($smsunit = $su->fetch())
                        {
                            $smsunits[] = $smsunit;
                            if($incode == $smsunit->item->value->code->value)
                            {
                                $operators++;
                            }
                        }
                        reset($smsunits);
                        if($operators > 0)
                        {
                            ?><select name="phoneoperator" onchange="document.formbuy.buynext.disabled=false;">
                            <option value=""></option>
                            <?php
                            foreach($smsunits as $smsunit)
                            {
                                if($incode == $smsunit->item->value->code->value)
                                {
                                    $phone_operator_title = $smsunit->phoneoperator->value->title->value;
                                    $phone_operator_id = $smsunit->phoneoperator->value->id;
                                    ?>
                                        <option value="<?php echo $phone_operator_id; ?>">
                                        <?php echo $phone_operator_title; ?></option>
                                    <?php
                                }
                            }
                            ?></select><?php
                        }
                        else
                        {
                            startnicewindow("Внимание", "_silver");
                            ?>Извините, нет ни одного оператора,
                            через которого можно купить
                            выбранный Вами шанс.<?php
                            endnicewindow();
                        }
                    $tbl2->newcol();
                        ?>
                        <input type="hidden" name="paymentmethod" value="2">
                        <input type="hidden" name="incode" value="<?php echo $incode ?>">
                        <input type="hidden" name="step" value="5">
                        <input type="hidden" name="stepfrom" value="2">
                        <input type="submit" name="back" value="&larr; Назад">
                        <?php if($operators <> 0) { ?>
                        <input type="submit" id="buynext" value="Далее &rarr;">
                        <?php }
                    $tbl2->end();
                    if($operators <> 0) { ?>
                    <script type="text/javascript">
                        document.formbuy.buynext.disabled=true;
                    </script>
                    <?php }
                break;
            case 5: // оплата смс-кой товара $_REQUEST['incode']
                    $incode = $_REQUEST['incode'];
                    if(!IsMarketItemCode($incode))
                    {
                        ?>
                        {{nicewindow style=silver caption=Ошибка}}
                        <p>Для покупки выбран несуществующий товар.</p>
                        <input type="hidden" name="stepfrom" value="1">
                        <input type="submit" name="back" value="&larr; Назад">
                        {{/nicewindow}}
                        <?php
                        break;
                    }
                    $chipsname = getChipsName($incode);
                    $phoneoperator_id = (int)$_REQUEST['phoneoperator'];
                    $phoneoperator = null;
                    $smsunits = $mikron->Queries->QueryAsArray('SMS_BILLING_UNIT');
                    foreach($smsunits as $smsunit)
                    {
                        if($smsunit->phoneoperator->value->id == $phoneoperator_id)
                        {
                            $phoneoperator = $smsunit->phoneoperator->value;
                        }
                    }
                    if($phoneoperator == null)
                    {
                        ?>
                        {{nicewindow style=silver caption="Ошибка"}}
                        <p>Для покупки выбран несуществующий оператор.</p>
                        <input type="hidden" name="incode" value="<?php echo $incode ?>">
                        <input type="hidden" name="paymentmethod" value="2">
                        <input type="hidden" name="stepfrom" value="4">
                        <input type="submit" name="back" value="&larr; Назад">
                        {{/nicewindow}}
                        <?php
                        break;
                    }
                    ?>
                    {{nicewindow style=silver caption="Покупка"}}
                    <?php
                    reset($smsunits);
                    foreach($smsunits as $smsunit)
                    {
                        if(($incode == $smsunit->item->value->code->value) && ($smsunit->phoneoperator->value->id == $phoneoperator_id))
                        {
                            $smscode = $smsunit->smscode->value;
                            $smsunit->smscode->value = str_replace("{{cabinet}}", $cabinet->login->value, $smscode);
                            echo $smsunit->toString();
                            $smsunit->smscode->value = $smscode;
                            break;
                        }
                    }                    
                    ?><p><input type="submit" name="cancel" value="Завершить покупку"></p>
                    {{/nicewindow}}
                    <?php
                break;
            case 3:
                if(!isset($_REQUEST['incode']) || !isset($_REQUEST['quantity']) || !is_numeric($_REQUEST['quantity']) || !IsMarketItemCode($_REQUEST['incode']))
                {
                    $error_text = IsMarketItemCode($_REQUEST['incode']) ? "Форма покупки заполнена неверно. Попробуйте еще." : "Попытка взлома. Данный факт занесен в учетную книгу";
                    ?>
                    {{nicewindow style=silver caption="Ошибка"}}
                    <?php echo "<p>$error_text</p>"; ?>
                    <input type="hidden" name="paymentmethod" value="3">
                    <input type="hidden" name="stepfrom" value="2">
                    <input type="submit" name="back" value="&larr; Назад">
                    {{/nicewindow}}
                    <?php
                    break;
                }
                $incode = $_REQUEST['incode'];
                $quantity = (int)$_REQUEST['quantity'];
                while($chip = $chips->fetch())
                {
                    $code = $chip->code->value;
                    if($incode == $code)
                    {
                        $forsale = $chip->forsale->value;
                        if(!$forsale)
                        {
                            ?>
                                {{nicewindow style=silver caption="Внимание"}}
                                <p>Данный товар не продается.</p>
                                <input type="hidden" name="paymentmethod" value="3">
                                <input type="hidden" name="stepfrom" value="2">
                                <input type="submit" name="back" value="&larr; Назад">
                                {{/nicewindow}}
                            <?php
                            break;
                        }
                        $amount = $chip->amount->value;
                        $amount_sum = $amount * $quantity;
                        $cabinetamount = $cabinet->amount->value;
                        if($cabinetamount < $amount_sum)
                        {
                            ?>{{nicewindow style=error caption="Информация"}}
                            <p>Недостаточно денег на балансе для покупки на сумму
                            <?php echo round($amount_sum/100, 2); ?> руб.</p>
                            <input type="hidden" name="paymentmethod" value="3">
                            <input type="hidden" name="quantity" value="<?php echo $quantity; ?>">
                            <input type="hidden" name="stepfrom" value="2">
                            <input type="submit" name="back" value="&larr; Назад">
                            {{/nicewindow}}
                            <?php
                            break;
                        }
                        else
                        {
                            try
                            {
                                
                                $foplog = ChangeCabinetBalance($cabinet, 1, 0, 0, 0, 0, 0);
                                $foplog->$incode->value = $quantity;
                                $foplog->amount->value = -$amount_sum;
                                OperationLogEcp($foplog, $cabinet);
                                $cabinet->amount->value -= $amount_sum;
                                $cabinet->$incode->value += $quantity;
                                $mikron->EntityManager->Save(Array($foplog, $cabinet));
                                ob_clean();
                                header("Location: index.php?ok=buy");
                                exit;
                            }
                            catch(Exception $ex)
                            {
                                ?>
                                <p>Ошибка при проведении платежа. Попробуйте еще раз.</p>
                                <input type="submit" name="back" value="&larr; Назад">
                                <?php
                                break;
                            }
                        }
                    }
                }
                break;
        }
        endxform();
    }
    
    function IsPaymentMethod($code)
    {
        global $mikron;
        $payment_methods = $mikron->Enumerators->getEnum('PAYMENT_METHODS');
        foreach($payment_methods as $pm)
        {
            if($pm['value']==$code)
            {
                return true;
            }
        }
        return false;
    }

    function IsMarketItemCode($code)
    {
        global $mikron;
        try
        {
            $marketitems = $mikron->Queries->Query('MARKET_ITEM');
            while($item = $marketitems->fetch())
            {
                if($item->code->value == $code)
                {
                    return true;
                }
            }
            return false;
        }
        catch(Exception $ex)
        {
            return false;
        }
    }
    
    function GetMarketItemByCode($code)
    {
        global $mikron;
        $item = $mikron->Queries->Query('MARKET_ITEM', null, new Criterion('code', $code));
        if($item->count() == 0)
        {
            return null;
        }
        return $item->fetch();
    }

    function OperationLogEcp($oplog, $cab, $partner = null)
    {
        global $mikron;
        $amount = $oplog->amount->value;
        $source = $oplog->source->value;
        $platinum = $oplog->platinum->value;
        $gold = $oplog->gold->value;
        $silver = $oplog->silver->value;
        $bronze = $oplog->bronze->value;
        $cabid = $cab->id;
        $dt = $oplog->dt->value;
        $dt = date($mikron->Constants->DateTimeFormat, strtotime($oplog->dt->value));
        if(is_object($partner))
        {
            $oplog->partner->value = $partner->id;
        }
        $oplog->ecp->value = md5("$cabid $source $amount $platinum $gold $silver $bronze $dt");
    }

    function ChangeCabinetBalance($cab, $source, $amount, $platinum, $gold, $silver, $bronze)
    {
        // лог всех финансовых операций
        $oplog = new T_OPERATIONS_LOG();
        $oplog->cabinet->value = $cab->id;
        $oplog->source->value = $source;
        $oplog->amount->value = $amount;
        $oplog->platinum->value = $platinum;
        $oplog->gold->value = $gold;
        $oplog->silver->value = $silver;
        $oplog->bronze->value = $bronze;
        $cab->amount->value += $amount;
        $cab->platinum->value += $platinum;
        $cab->gold->value += $gold;
        $cab->silver->value += $silver;
        $cab->bronze->value += $bronze;
        return $oplog;
    }

?>